import Data from "../object/Data"
import { setOnStateFunc } from "../utils/ExpiringResource"
import funcUtil from "../utils/func.util"
import Snapshots from "../object/Snapshot"
export default class SnapshotsData extends Data {
  snapshots: Record<string, Snapshots>
  hydrate: Function
  constructor(e: Record<string, Snapshots>) {
    super()
    this.name = "snapshots"
    this.snapshots = {}
    for (const t in e) this.snapshots[t] = e[t].clone()
  }
  get(e: string) {
    return this.snapshots[e]
  }
  get collection() {
    return this.snapshots
  }
  add(e: Snapshots) {
    e.sid = this.validateSid(e.sid)
    this.snapshots[e.sid] = e
    this.updateOnStaleCallbacks()
    this.commit()
  }
  remove(e: Snapshots) {
    delete this.snapshots[e.sid]
    this.commit()
  }
  validateSid(e: string) {
    for (; !e || this.snapshots[e]; ) e = funcUtil.randomStr(11)
    return e
  }
  set onStale(e: Function) {
    this.hydrate = e
    this.updateOnStaleCallbacks()
  }
  updateOnStaleCallbacks() {
    this.hydrate &&
      setOnStateFunc(this.snapshots, async () => {
        const e = await this.hydrate()
        for (const t in this.snapshots) e && e[t] && this.snapshots[t].refresh(e[t])
      })
  }
}
